<template>
  <el-form-item name="谐音词字体" label="谐音词字体">
    <el-select filterable @change="loadFonts" allow-create="true" v-model="props.modelValue" placeholder="选择字体"
      class="m-2" size="large">
      <el-option v-for="item in fontFamilyoptions" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-upload v-model:file-list="fileList" action="" multiple :limit="5" accept=".ttf,.otf,.woff,.woff2"
      :http-request="uploadFile">
      <template #trigger>
        <el-button type="primary">选择本地字体</el-button>
      </template>

      <template #tip>
        <div class="el-upload__tip">
          仅支持ttf、otf、woff 和 woff2类型文件
        </div>
      </template>
    </el-upload>
  </el-form-item>
</template>

<script setup lang="ts">
import { ITEM_RENDER_EVT } from 'element-plus/es/components/virtual-list/src/defaults';
import { ref } from 'vue';
const vk = uni.vk;

const emits = defineEmits(['update:modelValue']);
const props = defineProps({
  modelValue: {
    type: String,
    default: ref('')
  },
})

const defaultFontFamilyList = [
  {
    label: '华文楷体',
    value: '华文楷体',
  },
  {
    label: '华文行楷',
    value: '华文行楷',
  },
  {
    label: 'Aa后浪行楷',
    value: 'Aa后浪行楷',
  },
  {
    label: '汉仪秀英体简',
    value: '汉仪秀英体简',
  },
  {
    label: '汉仪糯米团',
    value: '汉仪糯米团',
  },
  {
    label: '锐字温帅小可爱简',
    value: '锐字温帅小可爱简',
  },
  {
    label: '汉仪小公姓氏体',
    value: '汉仪小公姓氏体',
  },
  {
    label: '鸿雷板书简体',
    value: '鸿雷板书简体',
  },
];
const fontFamilyoptions = ref(defaultFontFamilyList);
const baseUrl = 'https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/avatar-client/font/'

const loadFonts = (value) => {
  const fontList = defaultFontFamilyList.map((item) => item.value);
  if (fontList.includes(value)) {
    const style = document.createElement('style');
    style.innerHTML = `@font-face {font-family: ${value}; src: url(${baseUrl}${value}.ttf);}`;
    document.head.appendChild(style);
  }
  emits('update:modelValue', value);
}

const fileList = ref([]);
const fileToBase64Async = (file) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e: any) => {
      resolve(e.target.result);
    };
  });
}

const uploadFile = async (e) => {
  const { file } = e;
  const fontFamily = file.name.replace(/\.[^/.]+$/, '');
  try {
    const fileBase64 = await fileToBase64Async(file);
    const style = document.createElement('style');
    style.innerHTML = `@font-face {font-family: ${fontFamily}; src: url(${fileBase64});}`;
    document.head.appendChild(style);
  } catch (err) {
    vk.toast('字体加载失败，请重试或者换个字体试试吧！');
  }

  const customFonts = fileList.value.map((f) => {
    const name = f.name.replace(/\.[^/.]+$/, '');
    return { label: name, value: name };
  });
  fontFamilyoptions.value = [...customFonts, ...defaultFontFamilyList]
}
</script>